//
// StoreNuke.Net -  http://www.storenuke.net
// Copyright (c) 2005
// by Robert J Collins ( info@storenuke.net ) of WillowTree Software, Inc. ( http://www.willowtreesoftware.com )
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//

using System;
using System.Configuration;
using System.IO;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using StoreNuke.StarterKit.Commerce.Controls;

namespace StoreNuke.StarterKit.Commerce.StoreControls
{
	/// <summary>
	///		Summary description for ProductAdmin.
	/// </summary>
	public class ProductAdmin : AdminControls
	{
		protected LinkButton btnDelete;
		protected Label lblSpacer3;
		protected LinkButton btnCacel;
		protected Label lblSpacer2;
		protected LinkButton btnSave;
		protected TextBox txtName;
		protected Label lblName;
		protected Label lblNavSpacer;
		protected DataGrid dgEditProducts;
		protected LinkButton btnEditProd;
		protected LinkButton btnNewProd;
		protected TextBox txtNumber;
		protected DropDownList ddlCategories;
		protected Label lblNumber;
		protected Label lblImage;
		protected Label lblCost;
		protected Label lblDescription;
		protected Image imgProdImage;
		protected Panel pnNewProd;
		protected Panel pnEditProd;
		protected ProductsDB prod = new ProductsDB();
		protected string redirectURL;
		protected Label lblCats;
		protected DropDownList ddlImage;
		protected TextBox txtCost;
		protected Label lblUpload;
		protected Button btnUpload;
		protected HtmlInputFile fbImageUpload;
		protected System.Web.UI.WebControls.RequiredFieldValidator rfvName;
		protected System.Web.UI.WebControls.RequiredFieldValidator rfvNumber;
		protected System.Web.UI.WebControls.RequiredFieldValidator rfvCost;
		protected System.Web.UI.WebControls.Label lblError;
		protected System.Web.UI.WebControls.RegularExpressionValidator rxCost;
		protected System.Web.UI.WebControls.CheckBox cbArchived;
		public TextedEditor TextedEditor1;

		private void Page_Load(object sender, EventArgs e)
		{
			//Get page URL
			redirectURL = "Default.aspx?scid=" + StoreControlID.ToString() + "&sctl=1";

			ControlTitle = "Product Admin";

			// Get Categories
			if(! Page.IsPostBack)
			{
				BindCategoryList();
				GetImages();
				SetImage();
				if(Request.QueryString["pid"] != null)
				{
					GetProductInfo(Convert.ToInt32(Request.QueryString["pid"]));
					IsDeleteVisible(true);
					Utilities.GetDeleteConfirmationScriptLinkButton(btnDelete,"");
				}
				else
				{
					IsDeleteVisible(false);
				}
			}
			BindProductGrid();
		}

		private void BindProductGrid()
		{
			dgEditProducts.DataSource = prod.GetAllProducts(Convert.ToInt32(ddlCategories.SelectedValue));
			dgEditProducts.DataBind();
		}

		private void BindCategoryList()
		{
			ddlCategories.DataSource = prod.GetAllProductCategories();
			ddlCategories.DataBind();
		}

		public string GetEditURL(string productID)
		{
			return "../" + redirectURL + "&pid=" + productID;
		}

		private void SetPNVisibility(bool editVisible)
		{
			pnNewProd.Visible = (!editVisible);
			pnEditProd.Visible = editVisible;
		}

		private void SetImage()
		{
			//If DDL is empty or no image is select (case of new prods) us default: "../ProductImages/image.gif"
			if((ddlImage.SelectedValue != null) && (ddlImage.SelectedValue != ""))
			{
				imgProdImage.ImageUrl = "../MakeThumb.aspx?ID=" + ddlImage.SelectedValue + "&W=" + ConfigurationSettings.AppSettings["MaxImageWidth"];
			}
			else
			{
				imgProdImage.ImageUrl = "../MakeThumb.aspx?ID=" + "image.gif" + "&W=" + ConfigurationSettings.AppSettings["MaxImageWidth"];
			}
		}

		private void GetImages()
		{
			ddlImage.Items.Clear();
			DirectoryInfo dir = new DirectoryInfo(Server.MapPath(".") + "\\ProductImages");
			foreach(FileInfo flChild in dir.GetFiles())
			{ 
				//Add File Name to Dropdown List
				ddlImage.Items.Add(flChild.Name.ToLower());
			}
			ddlImage.Items.Insert(0,new ListItem("<no image selected>", ""));
		}

		private void ImageUpload()
		{
			if((fbImageUpload.PostedFile != null ) && ( fbImageUpload.PostedFile.ContentLength > 0 ))
			{
				string fn = Path.GetFileName(fbImageUpload.PostedFile.FileName);
				//fn = fn.Substring(0,fn.IndexOf("."));
				string dir = Server.MapPath(".") + "\\ProductImages\\";
				try
				{
					fbImageUpload.PostedFile.SaveAs(dir + fn);
					GetImages();
					FindImage(fn);
				}
				catch(Exception ex)
				{
					fn = ex.Message;
				}
			}
		}

		private void FindImage(string fn)
		{
			try
			{
				ddlImage.ClearSelection();
				ddlImage.Items.FindByValue(fn.ToLower()).Selected = true;
			}
			catch
			{
			}
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		/// <summary>
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.btnNewProd.Click += new System.EventHandler(this.btnNewProd_Click);
			this.btnEditProd.Click += new System.EventHandler(this.btnEditProd_Click);
			this.ddlCategories.SelectedIndexChanged += new System.EventHandler(this.ddlCategories_SelectedIndexChanged);
			this.ddlImage.SelectedIndexChanged += new System.EventHandler(this.ddlImage_SelectedIndexChanged);
			this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
			this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
			this.btnCacel.Click += new System.EventHandler(this.btnCacel_Click);
			this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click);
			this.Load += new System.EventHandler(this.Page_Load);

		}
		#endregion

		private void ddlCategories_SelectedIndexChanged(object sender, EventArgs e)
		{
			BindProductGrid();
		}

		private void btnNewProd_Click(object sender, EventArgs e)
		{
			SetPNVisibility(false);
			lblError.Visible = false;
		}

		private void btnEditProd_Click(object sender, EventArgs e)
		{
			SetPNVisibility(true);
		}

		private void ddlImage_SelectedIndexChanged(object sender, EventArgs e)
		{
			SetImage();
		}

		private void btnUpload_Click(object sender, EventArgs e)
		{
			ImageUpload();
			SetImage();
		}

		private void GetProductInfo(int pid)
		{
			//First Switch Panels
			SetPNVisibility(false);

			//Next Get Product Info
			Commerce.ProductDetails pd = prod.GetProductDetails(pid);
			
			if(pd != null)
			{
				txtName.Text = pd.ModelName;
				txtNumber.Text = pd.ModelNumber;
				FindImage(pd.ProductImage);
				SetImage();
				txtCost.Text = pd.UnitCost.ToString("#,##0.00");
				TextedEditor1.TextData = pd.Description;
				ddlCategories.SelectedValue = pd.CategoryID.ToString();
				cbArchived.Checked = pd.Archived;
			}
		}

		private void btnSave_Click(object sender, EventArgs e)
		{
			if(Request.QueryString["pid"] != null)
			{
				//update
				prod.UpdateProduct(Convert.ToInt32(Request.QueryString["pid"]),
					Convert.ToInt32(ddlCategories.SelectedValue),
					txtNumber.Text,
					txtName.Text,
					ddlImage.SelectedValue,
					Convert.ToDecimal(txtCost.Text),
					TextedEditor1.TextData, 
					cbArchived.Checked);
				Response.Redirect(redirectURL);
			}
			else
			{
				//insert
				prod.AddProduct(Convert.ToInt32(ddlCategories.SelectedValue),
					txtNumber.Text,
					txtName.Text,
					ddlImage.SelectedValue,
					Convert.ToDecimal(txtCost.Text),
					TextedEditor1.TextData, 
					cbArchived.Checked);
				BindCategoryList();
				ClearProductInfo();
			}
		}

		private void btnCacel_Click(object sender, EventArgs e)
		{
			Response.Redirect(redirectURL);
		}

		private void btnDelete_Click(object sender, EventArgs e)
		{
			//Delete
			int message = 0;
			if(Request.QueryString["pid"] != null)
			{
				try
				{
					message = prod.DeleteProduct(Convert.ToInt32(Request.QueryString["pid"]));
				}
				catch
				{
					lblError.Visible = true;
					lblError.Text = "Product has an order associated with it, it cannot be deleted";
				}

				if(message > 0)
				{
					lblError.Visible = true;
					lblError.Text = "Product has an order associated with it, it cannot be deleted";
				}
				else
				{
					Response.Redirect(redirectURL);
				}
			}
		}

		private void ClearProductInfo()
		{
			txtNumber.Text = "";
			txtName.Text = "";
			txtCost.Text = "";
			TextedEditor1.TextData = "";
			ddlImage.SelectedIndex = 0;
		}

		private void IsDeleteVisible(bool vis)
		{
			lblSpacer3.Visible = vis;
			btnDelete.Visible = vis;
		}
	}
}
